﻿using Azure.Core;
using DataModels.Dto;
using DataModels.Dto.AuthCore;
using DataModels.Entities.AuthCore;
using DataModels.Entities.Base;
using DataModels.Entities.WorkOrder;
using DataModels.Enums;
using DataModels.Enums.AuthCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using NetTaste;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Configuration;
using System.DirectoryServices.Protocols;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Net.Http.Json;
using System.Reflection;
using System.Security.Claims;
using System.Security.Cryptography.Xml;
using System.Text;
using Utils;
using static DataModels.Enums.AuthCore.UserEnum;
using static DataModels.Enums.GeneralEnum;
using static Dm.net.buffer.ByteArrayBuffer;

namespace Services.AuthCore
{
    public class OauthService(SqlSugarClient db, IConfiguration configuration, IMemoryCache memoryCache) : BaseService(db, configuration)
    {
        private readonly IMemoryCache _memoryCache = memoryCache;
        public async Task<ResponseModel> GetUserInfo()
        {
            List<User> users = await db.Queryable<User>().ToListAsync();
            return Success(users);
        }

        // 业主微信登录方法
        public async Task<ResponseModel> VxLogin(string code)
        {
            try
            {
                // 1. 通过code获取微信的access_token和openid
                var vxApiResult = await GetVxAccessTokenAndOpenId(code);

                if (string.IsNullOrEmpty(vxApiResult.OpenId))
                {
                    throw new Exception("获取微信OpenId失败");
                }

                // 2. 检查数据库中是否已有该openid的用户
                var user = await db.Queryable<Customer>()
                    .FirstAsync(u => u.VXOpenId == vxApiResult.OpenId);

                if (user == null)
                {
                    return Success("需调用获取手机号组件");

                }
                if (user.CustStatus != "1")
                {
                    return Error("用户已被禁用，请联系物业");
                }

                //商城系统对接
                jjjshop_user jjjuser = db.Queryable<jjjshop_user>()
                    .First(u => u.wx_id == vxApiResult.OpenId);
                if (jjjuser == null)
                {
                    jjjshop_user jjjuser1 = new jjjshop_user
                    {
                        wx_id = vxApiResult.OpenId,
                        create_time = DateTime.Now,
                        nickName = "买家-" + user.Tel1
                    };
                    jjjuser = db.Insertable(jjjuser1).ExecuteReturnEntity();
                }

                var claimsIdentity = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim("guid",user.UUID.ToString()),
                    new Claim("displayName",user.Name),
                    new Claim("account",user.VXOpenId),
                    new Claim("userType",UserEnum.RegisterType.WeChat.ToString()),
                    new Claim("aud","web"),
                    new Claim("iss","spring-boot-jjj"),
                    new Claim("jti",""),
                    new Claim("username",jjjuser.user_id.ToString()),
                });
                var token = GetJwtAccessToken(claimsIdentity);
                return Success(token);
            }
            catch (Exception e)
            {
                return Error("登陆失败：" + e.Message);
            }
        }

        // 业主微信登录注册
        public async Task<ResponseModel> VxLoginOrRegister(string code, string encryptedData, string iv)
        {
            try
            {
                // 1. 通过code获取微信的access_token和openid
                var vxApiResult = await GetVxAccessTokenAndOpenId(code);

                if (string.IsNullOrEmpty(vxApiResult.OpenId))
                {
                    throw new Exception("获取微信OpenId失败");
                }

                // 2. 检查数据库中客户表是否已有该openid的用户
                var user = await db.Queryable<Customer>()
                    .FirstAsync(u => u.VXOpenId == vxApiResult.OpenId);

                if (user == null)
                {
                    // 用户不存在，调用微信注册方法
                    string PhoneNumber = DecryptPhoneNumber(vxApiResult.session_key, encryptedData, iv);
                    //通过手机号查询四格数据中是否有该用户信息
                    user = await db.Queryable<Customer>().FirstAsync(u => (u.Tel1 == PhoneNumber || u.Tel2 == PhoneNumber) && (u.CustStatus == "1"));
                    if (user == null)
                    {
                        //return Error("未注册。如果你是业主请联系物业核对手机号");

                        user = await VxRegister(vxApiResult, PhoneNumber);
                    }
                    else
                    {
                        user.VXOpenId = vxApiResult.OpenId;
                        await db.Updateable<Customer>().SetColumns(x => x.VXOpenId == vxApiResult.OpenId).Where(x => x.UUID == user.UUID).ExecuteCommandAsync();
                    }

                }
                if (user.CustStatus != "1")
                {
                    return Error("用户已被禁用，请联系管理员");
                }

                //商城系统对接
                jjjshop_user jjjuser = db.Queryable<jjjshop_user>()
                    .First(u => u.wx_id == vxApiResult.OpenId);
                if (jjjuser == null) {
                    jjjshop_user jjjuser1 = new jjjshop_user
                    {
                        wx_id = vxApiResult.OpenId,
                        create_time = DateTime.Now,
                        nickName = "买家-" + user.Tel1
                    };
                    jjjuser = db.Insertable(jjjuser1).ExecuteReturnEntity();
                }

                var claimsIdentity = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim("guid",user.UUID.ToString()),
                    new Claim("displayName",user.Name),
                    new Claim("account",user.VXOpenId),
                    new Claim("userType",UserEnum.RegisterType.WeChat.ToString()),
                    new Claim("aud","web"),
                    new Claim("iss","spring-boot-jjj"),
                    new Claim("jti",""),
                    new Claim("username",jjjuser.user_id.ToString()),
                });
                var token = GetJwtAccessToken(claimsIdentity);
                return Success(token);
            }
            catch (Exception e)
            {
                return Error("登陆失败：" + e.Message);
            }
        }

        // 商家微信登录方法
        public async Task<ResponseModel> merchantsVxLogin(string code)
        {
            try
            {
                // 1. 通过code获取微信的access_token和openid
                var vxApiResult = await GetVxAccessTokenAndOpenId(code);

                if (string.IsNullOrEmpty(vxApiResult.OpenId))
                {
                    throw new Exception("获取微信OpenId失败");
                }

                // 2. 检查数据库中是否已有该openid的用户
                var user = await db.Queryable<User>()
                    .FirstAsync(u => u.VXOpenId == vxApiResult.OpenId);

                if (user == null)
                {
                    return Success("需调用获取手机号组件");

                }

                //商城系统对接
                jjjshop_user jjjuser = db.Queryable<jjjshop_user>()
                    .First(u => u.wx_id == vxApiResult.OpenId);
                if (jjjuser == null)
                {
                    jjjshop_user jjjuser1 = new jjjshop_user
                    {
                        wx_id = vxApiResult.OpenId,
                        create_time = DateTime.Now,
                        nickName = "商家-" + user.Phone
                    };
                    jjjuser = db.Insertable(jjjuser1).ExecuteReturnEntity();
                }

                var claimsIdentity = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.DisplayName),
                    new Claim("guid",user.UUID.ToString()),
                    new Claim("displayName",user.DisplayName),
                    new Claim("account",user.VXOpenId),
                    new Claim("userType",UserEnum.RegisterType.WeChat.ToString()),
                    new Claim("aud","web"),
                    new Claim("iss","spring-boot-jjj"),
                    new Claim("jti",""),
                    new Claim("username",jjjuser.user_id.ToString()),
                });
                var token = GetJwtAccessToken(claimsIdentity);
                return Success(token);
            }
            catch (Exception e)
            {
                return Error("登陆失败：" + e.Message);
            }
        }

        // 商户微信登录注册
        public async Task<ResponseModel> merchantsVxLoginOrRegister(string code, string encryptedData, string iv)
        {
            try
            {
                // 1. 通过code获取微信的access_token和openid
                var vxApiResult = await GetVxAccessTokenAndOpenId(code);

                if (string.IsNullOrEmpty(vxApiResult.OpenId))
                {
                    throw new Exception("获取微信OpenId失败");
                }

                // 2. 检查数据库中客户表是否已有该openid的用户
                var user = await db.Queryable<User>()
                    .FirstAsync(u => u.VXOpenId == vxApiResult.OpenId);

                if (user == null)
                {
                    // 用户不存在，调用微信注册方法
                    string PhoneNumber = DecryptPhoneNumber(vxApiResult.session_key, encryptedData, iv);
                    //通过手机号查询四格数据中是否有该用户信息
                    user = await db.Queryable<User>().FirstAsync(u => u.Phone == PhoneNumber);
                    if (user == null)
                    {
                        return Error("未注册。商户禁止微信自注册");
                        //user = new User
                        //{
                        //    UUID = Guid.NewGuid(),
                        //    Phone = PhoneNumber,
                        //    DisplayName = "商户用户_" + vxApiResult.OpenId.SafeSubstringLeft(7),
                        //    VXOpenId = vxApiResult.OpenId
                           
                        //};
                        //await db.Insertable(user).ExecuteCommandAsync();
                    }
                    else
                    {
                        user.VXOpenId = vxApiResult.OpenId;
                        await db.Updateable<User>().SetColumns(x => x.VXOpenId == vxApiResult.OpenId).Where(x => x.UUID == user.UUID).ExecuteCommandAsync();
                    }

                }

                //商城系统对接
                jjjshop_user jjjuser = db.Queryable<jjjshop_user>()
                    .First(u => u.wx_id == vxApiResult.OpenId);
                if (jjjuser == null) {
                    jjjshop_user jjjuser1 = new jjjshop_user
                    {
                        wx_id = vxApiResult.OpenId,
                        create_time = DateTime.Now,
                        nickName = "商家-" + user.Phone
                    };
                    jjjuser = db.Insertable(jjjuser1).ExecuteReturnEntity();
                }

                var claimsIdentity = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.DisplayName),
                    new Claim("guid",user.UUID.ToString()),
                    new Claim("displayName",user.DisplayName),
                    new Claim("account",user.VXOpenId),
                    new Claim("userType",UserEnum.RegisterType.WeChat.ToString()),
                    new Claim("aud","web"),
                    new Claim("iss","spring-boot-jjj"),
                    new Claim("jti",""),
                    new Claim("username",jjjuser.user_id.ToString()),
                });
                var token = GetJwtAccessToken(claimsIdentity);
                return Success(token);
            }
            catch (Exception e)
            {
                return Error("登陆失败：" + e.Message);
            }
        }

        public async Task<ResponseModel> SubmitTrial(string code, string encryptedData, string iv)
        {
            // 1. 通过code获取微信的access_token和openid
            var vxApiResult = await GetVxAccessTokenAndOpenId(code);
            // 用户手机号
            string PhoneNumber = DecryptPhoneNumber(vxApiResult.session_key, encryptedData, iv);
            var c_user = db.Queryable<Customer>().Where(x => x.Tel1 == PhoneNumber && x.CustId > 0).First();
            if (c_user != null)
            {
                return Success("业主用户，请直接登录！");
            }


            var info = db.Queryable<TrialUser>().Where(x => x.Phone == PhoneNumber).First();
            if (info != null)
            {
                return Success("请勿反复申请！");
            }
            var res = new TrialUser()
            {
                Phone = PhoneNumber,
                State = 0,
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now
            };
            db.Insertable(res).ExecuteCommand();
            return Success("申请成功！");
        }

        public ResponseModel VxFWHBindXCX(string fwhopenid)
        {
            var customer = db.Queryable<Customer>().Where(c => c.UUID == UserUUID).First();
            if (customer == null)
                return Error("用户未登录");

            customer.mpopen_id = fwhopenid;
                      
            db.Updateable(customer).ExecuteCommand();
            return Success("绑定成功！");
        }

        private string DecryptPhoneNumber(string sessionKey, string encryptedData, string iv)
        {
            try
            {
                // 使用AES解密算法，需遵循微信数据解密规范
                // 此处应使用官方提供的解密库（如WXBizDataCrypt.cs）
                var decryptor = new WXBizDataCrypt(configuration["AppSettings:VXappId"], sessionKey);
                var result = decryptor.Decrypt(encryptedData, iv);
                VXPhNumber phoneObj = JsonConvert.DeserializeObject<VXPhNumber>(result);
                return phoneObj.PhoneNumber;
            }
            catch (Exception ex)
            {
                throw new Exception("手机号解密失败", ex);
            }
        }

        // 微信注册方法
        private async Task<Customer> VxRegister(VxApiResult vxResult, string phone)
        {
            // 1. 获取微信用户信息
            var vxUserInfo = await GetVxUserInfo(vxResult.AccessToken, vxResult.OpenId);

            // 2. 创建新用户
            Guid uuid = Guid.NewGuid();
            var newUser = new Customer
            {
                UUID = uuid,
                Tel1 = phone,
                Name = phone,
                VXOpenId = vxResult.OpenId,
                PicUrl = vxUserInfo.AvatarUrl,  //
                ThirdCustId = uuid.ToString(),   //
                EstablishDate = DateTime.Now,
                ChangeTime = DateTime.Now,
                CustStatus = "1",
                dataSources = "微信自注册"  //
            };
            await db.Insertable(newUser).ExecuteCommandAsync();
            return newUser;
        }


        public class LoginResult
        {
            public string access_token { get; set; }
        }

        // 调用微信API获取access_token和openid
        private async Task<VxApiResult> GetVxAccessTokenAndOpenId(string code)
        {
            using var httpClient = new HttpClient();

            // 替换为你的微信小程序AppId和AppSecret
            var appId = configuration["AppSettings:VXappId"];
            var appSecret = configuration["AppSettings:VXappSecret"];

            var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";

            var response = await httpClient.GetStringAsync(url);
            var result = JsonConvert.DeserializeObject<VxApiResult>(response);
            if (result.Errcode != 0)
                Console.WriteLine("小程序[jscode2session]接口失败:错误代码 " + result.Errcode + "  描述：" + result.Errmsg);

            return result;
        }

        public async Task<string> GetAccessToken(string appType)
        {
            try
            {
                // 判断是微信小程序还是微信服务号 取对应的 AppId和AppSecret
                var appId = configuration["AppSettings:VXappId"];  //小程序
                var appSecret = configuration["AppSettings:VXappSecret"]; //小程序
                if (appType == "fwh")
                {
                    appId = configuration["AppSettings:VXFWHappId"];  //服务号
                    appSecret = configuration["AppSettings:VXFWHappSecret"]; //服务号
                }

                // （需提前实现 AccessToken 缓存逻辑）

                string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(url);
                    if (response.IsSuccessStatusCode)
                    {
                        string content = await response.Content.ReadAsStringAsync();
                        JObject obj = JObject.Parse(content);
                        return obj["access_token"].ToString();
                    }
                    return null;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("换取AccessToken异常"+ex.Message);
                return null;
            }
        }

        // 调用微信API获取用户信息
        private async Task<VxUserInfo> GetVxUserInfo(string accessToken, string openId)
        {
            using var httpClient = new HttpClient();

            var url = $"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}";

            var response = await httpClient.GetStringAsync(url);
            var userInfo = JsonConvert.DeserializeObject<VxUserInfo>(response);

            return userInfo;
        }

        // 发送短信验证码
        public async Task<ResponseModel> SendSmsCode(string phoneNumber)
        {
            // 检查是否频繁发送
            var recentCodes = await db.Queryable<SmsVerificationCode>()
                .Where(c => c.PhoneNumber == phoneNumber
                         && c.CreateTime >= DateTime.Now.AddMinutes(-5)) // 查询5分钟内的记录
                .ToListAsync();

            if (recentCodes.Count >= 5) // 检查是否超过5次
            {
                // 计算最早可发送时间
                var earliestNextTime = recentCodes.Min(c => c.CreateTime).AddMinutes(5);
                var remainingSeconds = (int)Math.Ceiling((earliestNextTime - DateTime.Now).TotalSeconds);

                return Error($"验证码发送过于频繁，请在{remainingSeconds}秒后再试");
            }

            // 生成6位随机验证码
            var code = GenerateRandomCode();

            // 这里应该调用短信服务商API发送短信
            var isSent = await SendSmsViaProvider(phoneNumber, code);

            if (isSent)
            {
                // 保存验证码到数据库
                var smsCode = new SmsVerificationCode
                {
                    PhoneNumber = phoneNumber,
                    Code = code,
                    CreateTime = DateTime.Now,
                    IsUsed = GeneralEnum.Status.Disable
                };

                await db.Insertable(smsCode).ExecuteCommandAsync();
                return Success();
            }

            return Error("发送失败");
        }

        // 手机号密码登录
        public async Task<ResponseModel> PhonePasswordLogin(string phoneNumber, string password)
        {
            try
            {
                // 检查账号密码
                var user = await db.Queryable<User>()
                    .FirstAsync(u => u.LoginName == phoneNumber);
                if (user == null || !PasswordHasher.VerifyPassword(password, user.Password))
                {
                    return Error("用户或密码错误");
                }
                if (user.Status == UserStatus.Disable)
                {
                    return Error("用户已被禁用，请联系管理员");
                }

                if (user.IsHospital == 2) 
                {
                    //商城系统对接
                    string laobanopenid = "";
                    jjjshop_user jjjuser = db.Queryable<jjjshop_user>()
                        .First(u => u.wx_id == laobanopenid);
                    if (jjjuser == null)
                    {
                        return Error("该用户未绑定商户");
                    }

                    var claimsIdentity1 = new ClaimsIdentity(new Claim[]
                    {
                         new Claim(ClaimTypes.Name, user.DisplayName),
                         new Claim("guid",user.UUID.ToString()),
                         new Claim("displayName",user.DisplayName),
                         new Claim("account",user.Phone),
                         new Claim("userType",UserEnum.RegisterType.Phone.ToString()),
                         new Claim("aud","web"),
                         new Claim("iss","spring-boot-jjj"),
                         new Claim("jti",""),
                         new Claim("username",jjjuser.user_id.ToString()),
                    });
                    var token1 = GetJwtAccessToken(claimsIdentity1);
                    return Success(token1);
                }

                var claimsIdentity = new ClaimsIdentity(new Claim[]
               {
                new Claim(ClaimTypes.Name, user.DisplayName),
                new Claim("guid",user.UUID.ToString()),
                //new Claim("guid","4abbc186-3fb7-46f2-8962-d329c9716690"),
                new Claim("displayName",user.DisplayName),
                new Claim("account",user.Phone),
                new Claim("userType",UserEnum.RegisterType.Phone.ToString())
               });
                var token = GetJwtAccessToken(claimsIdentity);
                return Success(token);
            }
            catch (Exception e)
            {
                return Error("登录失败：" + e.Message);
            }
        }

        // 设置新密码
        public async Task<ResponseModel> SetNewPassword(Guid uuid, string phoneNumber, string code, string newPassword)
        {
            try
            {
                // 检查用户是否存在
                var user = await db.Queryable<User>()
                    .FirstAsync(u => u.Phone == phoneNumber && u.UUID == uuid);
                if (user == null)
                {
                    return Error("用户不存在");
                }
                // 验证验证码
                var validCode = await ValidateSmsCode(phoneNumber, code);

                if (validCode == null)
                {
                    return Error("无效的验证码");
                }

                // 标记验证码已使用
                await db.Updateable<SmsVerificationCode>()
                    .SetColumns(c => new SmsVerificationCode { IsUsed = GeneralEnum.Status.Enable })
                    .Where(c => c.Id == validCode.Id)
                    .ExecuteCommandAsync();

                // 更新密码
                user.Password = PasswordHasher.HashPassword(newPassword);
                await db.Updateable(user).UpdateColumns(u => new { u.Password }).ExecuteCommandAsync();
                return Success("密码更新成功");
            }
            catch (Exception e)
            {
                return Error("更新密码失败：" + e.Message);
            }
        }

        // 手机号验证码登录或注册
        public async Task<ResponseModel> PhoneCodeLoginOrRegister(string phoneNumber, string code, string password)
        {
            try
            {
                // 验证验证码
                var validCode = await ValidateSmsCode(phoneNumber, code);

                if (validCode == null)
                {
                    return Error("无效的验证码");
                }

                // 标记验证码已使用
                await db.Updateable<SmsVerificationCode>()
                    .SetColumns(c => new SmsVerificationCode { IsUsed = GeneralEnum.Status.Enable })
                    .Where(c => c.Id == validCode.Id)
                    .ExecuteCommandAsync();

                // 检查用户是否已存在
                var user = await db.Queryable<User>()
                    .FirstAsync(u => u.Phone == phoneNumber);

                if (user == null)
                {
                    // 新用户注册
                    user = new User
                    {
                        Password = string.IsNullOrEmpty(password) ? null : PasswordHasher.HashPassword(password),
                        // 默认登录账号为手机号
                        LoginName = phoneNumber,
                        Phone = phoneNumber,
                        DisplayName = "用户_" + phoneNumber.Substring(7),
                        RegisterType = UserEnum.RegisterType.Phone
                    };

                    user = await db.Insertable(user).ExecuteReturnEntityAsync();
                }
                if (user.Status == UserStatus.Disable)
                {
                    return Error("用户已被禁用，请联系管理员");
                }
                // 生成JWT Token
                var claimsIdentity = new ClaimsIdentity(new[]
                {
                new Claim(ClaimTypes.Name, user.DisplayName),
                new Claim("guid", user.UUID.ToString()),
                new Claim("displayName", user.DisplayName),
                new Claim("account", user.Phone),
                new Claim("userType", UserEnum.RegisterType.Phone.ToString())
            });

                var token = GetJwtAccessToken(claimsIdentity);
                return Success(token);
            }
            catch (Exception e)
            {
                return Error("登录或注册失败：" + e);
            }

        }

        // 验证短信验证码
        private async Task<SmsVerificationCode> ValidateSmsCode(string phoneNumber, string code)
        {
            return await db.Queryable<SmsVerificationCode>()
                .Where(c => c.PhoneNumber == phoneNumber
                         && c.Code == code
                         && c.ExpireTime > DateTime.Now
                         && c.IsUsed == Status.Disable)
                .FirstAsync();
        }

        // 生成随机验证码
        private string GenerateRandomCode()
        {
            Random random = new Random();
            return random.Next(100000, 999999).ToString();
        }

        // 调用短信服务商API
        private async Task<bool> SendSmsViaProvider(string phoneNumber, string code)
        {
            // 替换为真实的短信服务商API调用
            Console.WriteLine($"模拟发送短信验证码: {code} 到 {phoneNumber}");
            return true;
        }

        private string GetJwtAccessToken(ClaimsIdentity claimsIdentity)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(configuration["AppSettings:Secret"]);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = claimsIdentity,
                Expires = DateTime.UtcNow.AddDays(3),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

        // 已登录账号绑定vx
        public async Task<ResponseModel> BindWeChat(Guid uid, string code)
        {

            User model = await db.Queryable<User>().Where(u => u.UUID == uid).FirstAsync();
            VxApiResult vxApiResult = await GetVxAccessTokenAndOpenId(code);

            if (string.IsNullOrEmpty(vxApiResult.OpenId))
            {
                throw new Exception("获取微信OpenId失败");
            }

            // 2. 检查数据库中是否已有该openid的用户
            if (await db.Queryable<User>().Where(u => u.VXOpenId == vxApiResult.OpenId).AnyAsync())
            {
                return Error("微信绑定有其他账号");
            }
            model.VXOpenId = vxApiResult.OpenId;
            await db.Updateable(model).UpdateColumns(x => x.VXOpenId).ExecuteCommandAsync();
            return Success();
        }

        // 已登录账号绑定手机号
        public async Task<ResponseModel> BindPhone(string phoneNumber, string code)
        {
            User model = await db.Queryable<User>().Where(u => u.UUID == UserUUID).FirstAsync();
            if (model == null)
            {
                return Error("用户不存在");
            }
            // 验证验证码
            var validCode = await ValidateSmsCode(phoneNumber, code);
            if (validCode == null)
            {
                return Error("无效的验证码");
            }
            // 标记验证码已使用
            await db.Updateable<SmsVerificationCode>()
                .SetColumns(c => new SmsVerificationCode { IsUsed = GeneralEnum.Status.Enable })
                .Where(c => c.Id == validCode.Id)
                .ExecuteCommandAsync();

            // 检查手机号是否已被绑定
            var existingUser = await db.Queryable<User>().Where(u => u.Phone == phoneNumber && u.UUID != UserUUID).AnyAsync();
            if (existingUser)
            {
                return Error("手机号已绑定其他账号");
            }
            // 更新用户手机号
            model.Phone = phoneNumber;
            await db.Updateable(model).UpdateColumns(x => x.Phone).ExecuteCommandAsync();
            return Success();
        }

        // 账号注销
        public async Task<ResponseModel> CancelAccount(string code, string ip)
        {
            User user = await db.Queryable<User>().Where(u => u.UUID == UserUUID).FirstAsync();
            if (user == null)
            {
                return Error("账号不存在");
            }

            // 验证码校验
            var validCode = await ValidateSmsCode(user.Phone, code);
            if (validCode == null)
            {
                return Error("无效的验证码");
            }

            // 标记验证码已使用
            await db.Updateable<SmsVerificationCode>()
                .SetColumns(c => new SmsVerificationCode { IsUsed = GeneralEnum.Status.Enable })
                .Where(c => c.Id == validCode.Id)
                .ExecuteCommandAsync();

            try
            {
                // 开启事务
                await db.BeginTranAsync();

                // 写入删除记录
                var deletedRecord = new UserDeletedRecord
                {
                    UUID = user.UUID,
                    IP = ip,
                    Phone = user.Phone,
                    VXOpenId = user.VXOpenId,
                    LoginName = user.LoginName,
                    Password = user.Password,
                    DisplayName = user.DisplayName,
                    Email = user.Email,
                    AvatarUrl = user.AvatarUrl,
                    Gender = user.Gender,
                    Birthday = user.Birthday,
                    RegisterType = user.RegisterType,
                    Status = user.Status,
                    CreateTime = user.CreateTime,
                    IsHospital= user.IsHospital,
                    OrganiztionsUUID = user.OrganiztionsUUID,
                    PositionUUID = user.PositionUUID,
                    BuildIdS = user.BuildIdS
                };

                await db.Insertable(deletedRecord).ExecuteCommandAsync();

                // 删除用户记录
                await db.Deleteable<User>().Where(u => u.UUID == UserUUID).ExecuteCommandAsync();

                // 提交事务
                await db.CommitTranAsync();

                return Success("账号已成功注销");
            }
            catch (Exception ex)
            {
                // 回滚事务
                await db.RollbackTranAsync();
                return Error("账号注销失败，请稍后重试");
            }
        }
    }
}